#!/usr/bin/env node

const { execSync } = require('child_process');
const path = require('path');

const main = async () => {
  try {
    console.log('🚀 Starting test setup...');

    // Set environment
    process.env.NODE_ENV = 'test';

    // Clean up previous test artifacts
    console.log('🧹 Cleaning up previous test artifacts...');
    execSync('rm -rf ./dist ./coverage', { stdio: 'inherit' });

    // Run type checking
    console.log('📝 Running type checks...');
    execSync('tsc --project tsconfig.test.json --noEmit', { stdio: 'inherit' });

    // Run ESLint
    console.log('🔍 Running ESLint...');
    execSync('eslint . --ext .ts', { stdio: 'inherit' });

    // Run Prisma generate for test database
    console.log('🔄 Generating Prisma client...');
    execSync('prisma generate', { stdio: 'inherit' });

    // Run tests with coverage
    console.log('🧪 Running tests with coverage...');
    execSync(
      'jest --config=jest.config.ts --coverage --detectOpenHandles --forceExit',
      { stdio: 'inherit' }
    );

    console.log('✅ All tests completed successfully!');
    process.exit(0);
  } catch (error) {
    console.error('❌ Test run failed:', error.message);
    process.exit(1);
  }
};

// Execute main function
main().catch((error) => {
  console.error('Fatal error:', error);
  process.exit(1);
});
